package proxy.cglib_proxy.proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import proxy.cglib_proxy.dao.User;

import java.lang.reflect.Method;

/**
 * author: Veng Su
 * email: suveng@163.com
 * date: 2018/8/13 14:33
 */
public class CGLibProxy {
    public static User getProxy(){
        //1.创建CGLib核心类
        Enhancer enhancer=new Enhancer();
        //2. 制定需要代理的类，也就是父类
        enhancer.setSuperclass(User.class);
        //3. 设置回调函数
        enhancer.setCallback(new MethodInterceptor() {
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                if (method.getName().equals("say")){
                    System.out.println("我是增强内容");
                }
                return methodProxy.invokeSuper(o,objects);
            }
        });
        //4. 生成代理对象
        User userDaoProxy= (User) enhancer.create();
        return userDaoProxy;
    }

}
